<template>
  <div class="px-6 py-8 w-full md:w-[90%] lg:w-[80%] m-auto overflow-y-auto h-[calc(100vh-3.5rem)] relative hide-scrollbar">
    <transition 
      name="fade" 
      mode="out-in"
      enter-active-class="transition-all duration-300 ease-out" 
      leave-active-class="transition-none"
      enter-from-class="opacity-0" 
      enter-to-class="opacity-100"
      leave-from-class="opacity-100" 
      leave-to-class="opacity-0"
    >
      <UnitsList 
        v-if="!selectedUnitId" 
        :units="units" 
        @select-unit="selectUnit" 
      />
      
      <UnitDetail
        v-else
        :unit="currentUnit"
        :lessons="filteredLessons"
        :is-new-lesson-disabled="isNewLessonDisabled"
        :container-height="containerHeight"
        @back="selectedUnitId = null"
        @create-course="createNewCourse"
        @select-lesson="handleLessonClick"
      />
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { 
  getAllUnits,
  getUnitCourses,
  createUnitProgress,
} from '@/api/unit';
import { useModalStore } from '@/stores/modal';
import { useProgress } from '@/composables/useProgress';
import { useSettingsStore } from '@/stores/settings';
import UnitsList from './components/UnitsList.vue';
import UnitDetail from './components/UnitDetail.vue';

// Core setup
const router = useRouter();
const route = useRoute();
const modalStore = useModalStore();
const progressManager = useProgress();
const settingsStore = useSettingsStore();

// Constants
const CARD_CONFIG = {
  size: 160,
  verticalGap: 50,
};

// State
const selectedUnitId = ref(null);
const units = ref([]);
const allLessons = ref([]);

// Computed properties
const currentUnit = computed(() => units.value.find(unit => unit.id === selectedUnitId.value));
const filteredLessons = computed(() => allLessons.value);
const isNewLessonDisabled = computed(() => {
  if (filteredLessons.value.length === 0) return false;
  const lastLesson = filteredLessons.value[filteredLessons.value.length - 1];
  return lastLesson && !lastLesson.is_completed;
});
const containerHeight = computed(() => {
  const totalCards = filteredLessons.value.length + 1; // +1 for new button
  return `${totalCards * (CARD_CONFIG.size + CARD_CONFIG.verticalGap) + 24}px`;
});

// Data loading functions
const fetchVocabularyProgress = async () => {
  try {
    const response = await getAllUnits(settingsStore.bookType);
    if (response.code === 0) {
      units.value = formatUnitsData(response.data);
    }
  } catch (error) {
    console.error('获取单元信息出错:', error);
  }
};

const formatUnitsData = (data) => {
  return data.units.map(unit => ({
    id: unit.id.toString(),
    title: unit.name,
    locked: unit.level > 2,
    progress: progressManager.calculateProgress(unit.progresses?.words_learned, unit.progresses?.words_total),
    words: `${unit.progresses?.words_learned || 0}/${unit.word_count}`,
    description: unit.description,
    level: unit.level,
    order: unit.order
  }));
};

// Unit management functions
const saveLastOpenedUnit = (unitId) => {
  try {
    modalStore.setLastUnit(unitId.toString());
  } catch (error) {
    console.error('保存上次打开的单元失败:', error);
  }
};

const getLastOpenedUnit = () => {
  return modalStore.lastUnitId || null;
};

// Interaction handlers
const selectUnit = async (unitId) => {
  const unit = units.value.find(u => u.id === unitId);
  if (!unit || unit.locked) return;
  
  try {
    const response = await getUnitCourses(unitId);
    if (response.code === 0) {
      allLessons.value = formatCoursesData(response.data);
      updateSelectedUnit(unitId);
      
      nextTick(() => {
        scrollToLastCourse();
      });
    }
  } catch (error) {
    console.error('选择单元失败:', error);
    showToast('选择单元失败，请稍后重试', 'error');
  }
};

const formatCoursesData = (courses) => {
  return courses.map((course, index) => ({
    id: course.course_id,
    name: `第${index + 1}课`,
    unitId: course.unit_id,
    locked: false,
    progress: progressManager.calculateProgress(course.words_learned, course.words_total),
    words_learned: course.words_learned,
    words_total: course.words_total,
    is_completed: course.is_completed,
    last_studied_at: course.last_studied_at
  }));
};

const updateSelectedUnit = (unitId) => {
  selectedUnitId.value = unitId;
  router.push({ path: '/home/reading', query: { unit: unitId } });
  saveLastOpenedUnit(unitId);
};

const createNewCourse = async () => {
  try {
    const response = await createUnitProgress(selectedUnitId.value.toString());
    if (response.code === 0 && response.data) {
      addNewCourse(response.data);
      showToast('成功创建新课程', 'info');
    }
  } catch (error) {
    console.error('创建新课程失败:', error);
    showToast('请先完成上一关卡的文章', 'error');
  }
};

const addNewCourse = (courseData) => {
  const newCourse = {
    id: courseData.course_id,
    name: `第${allLessons.value.length + 1}课`,
    unitId: courseData.unit_id,
    locked: false,
    progress: 0,
    words_learned: 0,
    words_total: courseData.words_total || 0,
    is_completed: false,
    last_studied_at: null
  };
  allLessons.value.push(newCourse);
};

const handleLessonClick = (lesson) => {
  if (lesson.locked) return;
  modalStore.setLastCourse(lesson.id);
  router.push(`/home/reading/vocabulary/${lesson.id}`);
};

const scrollToLastCourse = () => {
  const lastCourseId = modalStore.lastCourseId;
  if (!lastCourseId || filteredLessons.value.length === 0) return;
  
  const courseIndex = filteredLessons.value.findIndex(lesson => lesson.id === lastCourseId);
  if (courseIndex === -1) return;
  
  const scrollPosition = courseIndex * (CARD_CONFIG.size + CARD_CONFIG.verticalGap);
  const scrollContainer = document.querySelector('.overflow-y-auto');
  if (scrollContainer) {
    scrollContainer.scrollTo({
      top: scrollPosition,
      behavior: 'smooth'
    });
  }
};

// Toast notifications
const showToast = (message, type = 'info') => {
  const toast = createToastElement(message, type);
  document.body.appendChild(toast);
  setTimeout(() => toast.remove(), 2500);
  return toast;
};

const createToastElement = (message, type) => {
  const toast = document.createElement('div');
  toast.className = `toast toast-${type}`;
  toast.textContent = message;
  
  Object.assign(toast.style, {
    position: 'fixed',
    top: '20px',
    left: '50%',
    transform: 'translateX(-50%)',
    padding: '10px 20px',
    borderRadius: '4px',
    backgroundColor: type === 'error' ? '#f44336' : '#333',
    color: 'white',
    zIndex: '9999',
    boxShadow: '0 2px 8px rgba(0,0,0,0.2)'
  });
  
  return toast;
};

// Lifecycle hooks
onMounted(async () => {
  if (!settingsStore.initialized) {
    await settingsStore.fetchSettings();
  }
  
  await fetchVocabularyProgress();
  initializeFromRoute();
});

const initializeFromRoute = () => {
  const { unit } = route.query;
  
  if (unit) {
    selectUnitIfValid(unit);
    return;
  }
  
  const lastOpenedUnit = getLastOpenedUnit();
  if (lastOpenedUnit) {
    selectUnitIfValid(lastOpenedUnit);
  }
};

const selectUnitIfValid = async (unitId) => {
  if (units.value.length === 0) {
    setTimeout(() => selectUnitIfValid(unitId), 100);
    return;
  }
  
  const stringUnitId = unitId.toString();
  const validUnit = units.value.find(u => u.id === stringUnitId && !u.locked);
  
  if (!validUnit) return;
  
  // Skip if already selected
  if (selectedUnitId.value === stringUnitId) return;
  
  try {
    const response = await getUnitCourses(stringUnitId);
    if (response.code === 0) {
      allLessons.value = formatCoursesData(response.data);
      selectedUnitId.value = stringUnitId;
      saveLastOpenedUnit(stringUnitId);
      
      nextTick(() => {
        scrollToLastCourse();
      });
    }
  } catch (error) {
    console.error('加载单元课程失败:', error);
  }
};

// Route watchers
watch(() => route.query.unit, (newUnit, oldUnit) => {
  if (!newUnit) {
    selectedUnitId.value = null;
    return;
  }
  
  if (newUnit === oldUnit) return;
  
  selectUnitIfValid(newUnit);
});

// Book type watcher
watch(() => settingsStore.bookType, async (newBookType, oldBookType) => {
  if (newBookType !== oldBookType) {
    selectedUnitId.value = null;
    await fetchVocabularyProgress();
  }
});
</script>

<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');

.font-inter {
  font-family: 'Inter', sans-serif;
}

.hide-scrollbar {
  -ms-overflow-style: none;
  scrollbar-width: none;
  &::-webkit-scrollbar {
    display: none;
  }
}

.fade-enter-active {
  transition: opacity 0.3s ease;
}

.fade-leave-active {
  transition: none;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style> 